package com.platform.framework.web.service.admin;

import com.alibaba.fastjson2.JSONObject;
import com.platform.common.constant.Constants;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.enums.UserStatus;
import com.platform.common.exception.ServiceException;
import com.platform.common.utils.MessageUtils;
import com.platform.common.utils.StringUtils;
import com.platform.system.domain.dto.TenantDto;
import com.platform.system.domain.vo.chip.TenantVo;
import com.platform.system.service.ISysTenantService;
import com.platform.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service("loginByPasswordService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    ISysTenantService sysTenantService;

    @Override
    public UserDetails loadUserByUsername(String loginUserInfo) throws UsernameNotFoundException {
        JSONObject jsonObject = JSONObject.parse(loginUserInfo);
        SysUser sysUser = new SysUser();
        //用户名称
        String username = jsonObject.getString("username");
        sysUser.setUserName(username);
        //传过来的租户信息
        if(jsonObject.containsKey("userType")){
            String userType = jsonObject.getString("userType");
            String tenantUid = jsonObject.getString("tenantUid");
            if(!Constants.STR_ZERO.equals(tenantUid)){
                TenantVo tenantVo = new TenantVo();

                //租户Uid
                tenantVo.setName(jsonObject.getString("tenantUid"));
                TenantDto tenantDto = sysTenantService.selectTenant(tenantVo);
                if(tenantDto == null){
                    throw new ServiceException(MessageUtils.message("tenant.not.exists"));
                }
            }
            sysUser.setTenantUid(tenantUid);
        }
        SysUser user = userService.selectUserByUserName(sysUser);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
        passwordService.validate(user);
        log.info("创建登陆用户{}", user.getTenantUid());
        return createLoginUser(user);
    }

    /**
     * 创建登陆用户
     * @param user
     * @return
     */
    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
